// utils/mock.js
// Mock数据服务 - 用于前端开发测试

const MockData = {
  // 用户相关Mock数据
  user: {
    login: {
      code: 200,
      data: {
        token: 'mock-token-' + Date.now(),
        userInfo: {
          id: 1,
          nickName: '测试用户',
          avatar: '/images/default-avatar.png',
          role: 'user',
          phone: '13800138000'
        }
      }
    },
    
    wechatLogin: {
      msg: '微信登录成功',
      code: 200,
      token: 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyXzI2NGUyMzNjIiwibG9naW5fdXNlcl9rZXkiOiIzZDQwMWQyZS0xY2I5LTQ5MDAtODUwNC0xNGIzMDYxYjkzZTkifQ.ccZUU0lTfbotZkzkCwEqpV9g-6rv12sBbMoJsv_yGmNXyWgWBxyWwEjaFTfOQHmI9etUvMiHD0AsYPwPvRg9_g'
    },
    
    getProfile: {
      msg: '操作成功',
      postGroup: '',
      code: 200,
      data: {
        userId: 105,
        userName: 'user_264e233c',
        nickName: '微信用户49682',
        email: 'user@example.com',
        phonenumber: '13800138000',
        sex: '0', // 0=未知, 1=男, 2=女
        avatar: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/f393f5c29478a7b382748e71c1d68ebb.png',
        status: '0',
        createBy: 'wechat',
        createTime: '2025-10-21 17:43:57',
        remark: '',
        roles: [
          {
            roleId: 2,
            roleName: '普通角色',
            roleKey: 'common',
            roleSort: 2,
            status: '0',
            admin: false
          }
        ]
      },
      roleGroup: '普通角色'
    },
    
    updateProfile: {
      msg: '修改成功',
      code: 200
    },
    
    getUserInfo: {
      code: 200,
      data: {
        id: 1,
        nickName: '测试用户',
        avatar: '/images/default-avatar.png',
        role: 'user',
        preferences: ['燃脂', '瑜伽'],
        stats: {
          watchTime: '12小时30分钟',
          completedCourses: 8,
          followers: 156,
          following: 23
        }
      }
    }
  },

  // 视频相关Mock数据
  video: {
    getList: {
      code: 200,
      data: {
        list: [
          {
            id: 1,
            title: '零基础燃脂HIIT',
            desc: '适合新手的燃脂训练，动作简单易学',
            cover: '/images/course1.jpg',
            duration: '20分钟',
            level: '初级',
            viewCount: 1234,
            tags: ['燃脂', 'HIIT', '新手'],
            isCollected: false,
            chapters: [
              { id: 1, title: '热身准备', duration: '5分钟', isCompleted: true },
              { id: 2, title: 'HIIT训练', duration: '12分钟', isCompleted: false },
              { id: 3, title: '拉伸放松', duration: '3分钟', isCompleted: false }
            ]
          }
        ],
        total: 1,
        page: 1,
        limit: 10
      }
    },

    getDetail: {
      code: 200,
      data: {
        id: 1,
        title: '零基础燃脂HIIT',
        desc: '适合新手的燃脂训练，动作简单易学，效果显著',
        cover: '/images/course1.jpg',
        duration: '20分钟',
        level: '初级',
        viewCount: 1234,
        tags: ['燃脂', 'HIIT', '新手'],
        isCollected: false,
        introduction: '这是一套专为运动新手设计的燃脂训练课程...',
        chapters: [
          {
            id: 1,
            title: '热身准备',
            duration: '5分钟',
            videoUrl: '/videos/warmup.mp4',
            isCompleted: true
          }
        ]
      }
    }
  },

  // 社区相关Mock数据
  community: {
    // 获取话题列表
    getTopicList: {
      msg: '操作成功',
      code: 200,
      data: [
        {
          topicId: 1,
          topicName: '核心肌群训练与腰椎稳定',
          topicDesc: '探讨核心肌群（腹横肌、多裂肌等）在维持腰椎稳定中的作用，以及如何安全有效地进行核心力量康复训练，预防和缓解下背痛。',
          postCount: 0,
          status: '0',
          createBy: '',
          createTime: '2025-11-05T15:50:25.000+08:00',
          updateBy: '',
          updateTime: '2025-11-05T15:50:25.000+08:00',
          remark: '适用于有慢性腰痛、术后恢复或需要提升运动表现的个体。'
        },
        {
          topicId: 2,
          topicName: '肩袖损伤后的安全康复训练',
          topicDesc: '介绍肩袖肌群的解剖与功能，讨论肩袖损伤（如肌腱炎、撕裂）急性期与慢性期的康复策略，包括活动度恢复、肌力强化与功能性训练。',
          postCount: 0,
          status: '0',
          createBy: '',
          createTime: '2025-11-05T15:50:40.000+08:00',
          updateBy: '',
          updateTime: '2025-11-05T15:50:40.000+08:00',
          remark: '适用于肩部疼痛、活动受限或有肩袖手术史的个体。'
        },
        {
          topicId: 3,
          topicName: 'ACL（前交叉韧带）重建术后康复阶梯',
          topicDesc: '详细规划ACL重建手术后从早期保护、中期力量恢复到后期重返运动的各阶段康复目标、训练方法和注意事项，强调神经肌肉控制的重要性。',
          postCount: 0,
          status: '0',
          createBy: '',
          createTime: '2025-11-05T15:51:00.000+08:00',
          updateBy: '',
          updateTime: '2025-11-05T15:51:00.000+08:00',
          remark: '专业性较强，适用于术后康复指导，需在专业人士指导下进行。'
        }
      ]
    },

    getPostList: {
      msg: '操作成功',
      code: 200,
      data: [
        {
          postId: 4,
          userId: 107,
          content: '早安打卡！今天的瑜伽晨练真的太舒服了🧘‍♀️ 感觉整个人都充满了能量！推荐给大家这套简单的拉伸动作，特别适合久坐的上班族~',
          imageUrls: '[https://design.gemcoder.com/staticResource/echoAiSystemImages/c6028ae9aff08b3818e5c6d448c37e81.png,https://design.gemcoder.com/staticResource/echoAiSystemImages/72a798a011746ce7e5bf5434d1a7f226.png,https://design.gemcoder.com/staticResource/echoAiSystemImages/0623c7a580d8110b2319fe65b06d4dd2.png]',
          likeCount: 89,
          commentCount: 15,
          collectCount: 23,
          shareCount: 8,
          viewCount: 345,
          status: '0',
          createBy: 'user_yoga_lover',
          createTime: '2025-11-08T08:30:00.000+08:00',
          updateBy: 'user_yoga_lover',
          updateTime: '2025-11-08T08:30:00.000+08:00',
          remark: '瑜伽晨练分享'
        },
        {
          postId: 3,
          userId: 106,
          content: '💪 今天跑步10公里达成！配速5分钟，感觉状态越来越好了。坚持就是胜利！',
          imageUrls: '[https://design.gemcoder.com/staticResource/echoAiSystemImages/9e3a9e313dbdfbc43e7582132f215e62.png]',
          likeCount: 156,
          commentCount: 28,
          collectCount: 12,
          shareCount: 5,
          viewCount: 512,
          status: '0',
          createBy: 'user_runner',
          createTime: '2025-11-07T19:20:00.000+08:00',
          updateBy: 'user_runner',
          updateTime: '2025-11-07T19:20:00.000+08:00',
          remark: '跑步打卡'
        },
        {
          postId: 2,
          userId: 105,
          content: '🌷【产后重塑与恢复】—— 盆底肌与腹直肌康复营\n为爱付出的您，值得更温柔的恢复。产后漏尿、腹部松弛、腰骶部疼痛？这些不是"正常现象"，而是身体发出的求助信号！',
          imageUrls: '[https://design.gemcoder.com/staticResource/echoAiSystemImages/03df6b95d93102f80b4590375a946ecf.png,https://design.gemcoder.com/staticResource/echoAiSystemImages/6552792502e92b5627709509cf5876c6.png]',
          likeCount: 234,
          commentCount: 67,
          collectCount: 89,
          shareCount: 23,
          viewCount: 1024,
          status: '0',
          createBy: 'user_264e233c',
          createTime: '2025-11-05T18:19:57.000+08:00',
          updateBy: 'user_264e233c',
          updateTime: '2025-11-05T18:19:57.000+08:00',
          remark: '针对产后盆底肌和腹直肌修复的康复课程文案。'
        },
        {
          postId: 1,
          userId: 105,
          content: '今天完成了第30天的核心训练挑战！腰围减少了5cm，继续加油！💪 #核心训练 #30天挑战',
          imageUrls: '[https://design.gemcoder.com/staticResource/echoAiSystemImages/5e34ad6ee6c742a1fd248d91b96bf3a6.png]',
          likeCount: 128,
          commentCount: 32,
          collectCount: 45,
          shareCount: 12,
          viewCount: 256,
          status: '0',
          createBy: 'user_health',
          createTime: '2025-11-05T18:19:40.000+08:00',
          updateBy: 'user_health',
          updateTime: '2025-11-05T18:19:40.000+08:00',
          remark: '健身打卡分享'
        }
      ]
    },

    // 根据话题ID获取动态列表
    getPostsByTopicId: {
      msg: '操作成功',
      code: 200,
      data: [
        {
          postId: 3,
          userId: 105,
          content: '核心肌群训练打卡第7天！今天做了腹横肌激活训练，感觉腰部更稳定了。坚持就是胜利！💪',
          imageUrls: '[https://design.gemcoder.com/staticResource/echoAiSystemImages/0623c7a580d8110b2319fe65b06d4dd2.png]',
          likeCount: 45,
          commentCount: 12,
          collectCount: 8,
          shareCount: 3,
          viewCount: 128,
          status: '0',
          createBy: 'user_264e233c',
          createTime: '2025-11-12T21:44:43.000+08:00',
          updateBy: 'user_264e233c',
          updateTime: '2025-11-12T21:44:43.000+08:00',
          remark: null
        }
      ]
    },
    
    getPostDetail: {
      msg: '查询成功',
      code: 200,
      data: {
        postId: 2,
        userId: 105,
        content: '### 🌷 文案四：【产后重塑与恢复】—— 盆底肌与腹直肌康复营\n主题：为爱付出的您，值得更温柔的恢复。\n痛点切入：产后漏尿、腹部松弛、腰骶部疼痛？这些不是"正常现象"，而是身体发出的求助信号！\n课程亮点：✅ 盆底肌评估与激活：安全有效的凯格尔训练升级版，告别尴尬。✅ 腹直肌分离修复：专业指导下的呼吸和核心收缩训练，重塑平坦小腹。✅ 骨盆稳定强化：改善因怀孕和分娩导致的骨盆移位和腰痛。✅ 恢复运动：科学规划产后恢复性有氧和力量训练。\n适合人群：产后42天复查通过的妈妈、有漏尿、腹直肌分离、产后腰痛等困扰的人士。\n号召行动：恢复的不只是身材，更是自信与健康！即刻咨询产后专属康复方案！',
        imageUrls: '[http://8.138.160.18:9000/trainvideo/post/images/60a12529-1e55-4637-9339-6fbf74db8bf9.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=create%2F20251105%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20251105T095400Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=3ed4a0dbc3b844e4ffc03147b6a0bbe27bddcc0f9241d72d981fc3613d3cd4c2,http://8.138.160.18:9000/trainvideo/post/images/4adbb6cb-d13a-4b92-a5bd-2a8c60683b41.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=create%2F20251105%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20251105T095400Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=79c9bfa9cae0bab2f5d86c8b99550e3ff5de71d9171afc925dc5a2e5ecdbc002]',
        likeCount: 128,
        commentCount: 32,
        collectCount: 15,
        shareCount: 8,
        viewCount: 257,
        status: '0',
        createBy: 'user_264e233c',
        createTime: '2025-11-05T18:19:57.000+08:00',
        updateBy: 'user_264e233c',
        updateTime: '2025-11-05T18:19:57.000+08:00',
        remark: '针对产后盆底肌和腹直肌修复的康复课程文案。'
      }
    },
    
    incrementViewCount: { msg: '操作成功', code: 200, data: { currentViewCount: 258 } },
    
    // 创建动态（带话题）
    createPost: { 
      msg: '发布成功', 
      code: 200,
      data: {
        postId: 999,
        userId: 105,
        content: '测试动态内容',
        imageUrls: '',
        likeCount: 0,
        commentCount: 0,
        collectCount: 0,
        shareCount: 0,
        viewCount: 0,
        status: '0',
        createBy: 'user_mock',
        createTime: new Date().toISOString(),
        updateBy: 'user_mock',
        updateTime: new Date().toISOString(),
        remark: null
      }
    },
    
    // 上传动态图片（Mock）
    uploadPostImages: {
      msg: '图片上传成功',
      code: 200,
      data: {
        url: [
          'https://design.gemcoder.com/staticResource/echoAiSystemImages/mock-image-1.png',
          'https://design.gemcoder.com/staticResource/echoAiSystemImages/mock-image-2.png'
        ]
      }
    },
    
    publishPost: { msg: '发布成功', code: 200 },
    likePost: { msg: '点赞成功', code: 200 },
    unlikePost: { msg: '已取消点赞', code: 200 },
    collectPost: { msg: '收藏成功', code: 200 },
    uncollectPost: { msg: '已取消收藏', code: 200 },
    
    // 获取动态评论列表
    getPostComments: {
      msg: '查询成功',
      code: 200,
      data: {
        list: [
          {
            id: 1,
            postId: 2,
            userId: 101,
            userName: '运动达人小王',
            userAvatar: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/9e3a9e313dbdfbc43e7582132f215e62.png',
            content: '这个产后康复课程真的很有帮助！跟着练了一周,盆底肌明显有改善。',
            likeCount: 23,
            isLiked: false,
            isMine: false,
            replyTo: null,
            createTime: 1730800800000, // 2小时前
            status: '0'
          },
          {
            id: 2,
            postId: 2,
            userId: 102,
            userName: '新手妈妈Lucy',
            userAvatar: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/8d270d8f47ca0541745913e4fa1640ca.png',
            content: '请问产后多久可以开始训练呀？我现在产后两个月了。',
            likeCount: 8,
            isLiked: false,
            isMine: false,
            replyTo: null,
            createTime: 1730714400000, // 1天前
            status: '0'
          },
          {
            id: 3,
            postId: 2,
            userId: 105,
            userName: '微信用户49682',
            userAvatar: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/f393f5c29478a7b382748e71c1d68ebb.png',
            content: '@新手妈妈Lucy 建议产后42天复查通过后再开始哦，安全第一！',
            likeCount: 15,
            isLiked: true,
            isMine: true,
            replyTo: '新手妈妈Lucy',
            createTime: 1730628000000, // 2天前
            status: '0'
          },
          {
            id: 4,
            postId: 2,
            userId: 103,
            userName: '健身教练Amy',
            userAvatar: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/c6028ae9aff08b3818e5c6d448c37e81.png',
            content: '专业的产后康复课程，动作编排很科学，点赞！👍',
            likeCount: 31,
            isLiked: false,
            isMine: false,
            replyTo: null,
            createTime: 1730541600000, // 3天前
            status: '0'
          },
          {
            id: 5,
            postId: 2,
            userId: 104,
            userName: '康复学员小美',
            userAvatar: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/0623c7a580d8110b2319fe65b06d4dd2.png',
            content: '跟着练了一个月，腹直肌分离从3指缩小到1指了，太开心了！',
            likeCount: 42,
            isLiked: true,
            isMine: false,
            replyTo: null,
            createTime: 1730455200000, // 4天前
            status: '0'
          }
        ],
        total: 32,
        page: 1,
        pageSize: 20
      }
    },
    
    // 添加评论
    addPostComment: { msg: '评论成功', code: 200, data: { commentId: Date.now() } },
    
    // 点赞评论
    likeComment: { msg: '点赞成功', code: 200 },
    unlikeComment: { msg: '已取消点赞', code: 200 },
    
    // 删除评论
    deleteComment: { msg: '删除成功', code: 200 }
  },

  // 评论相关Mock数据
  comment: {
    getList: {
      code: 200,
      data: {
        list: [
          {
            id: 1,
            userName: '运动达人小王',
            userAvatar: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/9e3a9e313dbdfbc43e7582132f215e62.png',
            content: '课程很棒！动作讲解很详细，适合新手学习。',
            time: '2小时前',
            likeCount: 12,
            isLiked: false
          },
          {
            id: 2,
            userName: '健身小白',
            userAvatar: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/8d270d8f47ca0541745913e4fa1640ca.png',
            content: '坚持就是胜利！加油！',
            time: '1天前',
            likeCount: 5,
            isLiked: false
          }
        ],
        total: 2,
        page: 1,
        limit: 10
      }
    },
    add: { msg: '评论成功', code: 200 }
  },

  // 管理员相关Mock数据
  admin: {
    getOverview: {
      code: 200,
      data: {
        totalUsers: 1234,
        totalVideos: 567,
        totalPosts: 890,
        todayActive: 234
      }
    },

    getPendingList: {
      code: 200,
      data: {
        list: [
          {
            id: 1,
            type: '视频',
            title: '新手燃脂训练课程',
            time: '2小时前',
            status: 'pending'
          }
        ],
        total: 1
      }
    }
  }
};

// Mock API服务
class MockService {
  constructor() {
    this.isMockMode = true; // 设置为true启用Mock模式
  }

  // 模拟网络延迟
  delay(ms = 500) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  // 模拟API请求
  async request(url, options = {}) {
    if (!this.isMockMode) {
      // 真实API请求
      return this.realRequest(url, options);
    }

    // Mock请求
    await this.delay();
    
    const path = url.replace('/api', '');
    const mockData = this.getMockData(path, options.method);
    
    if (mockData) {
      return mockData;
    }
    
    return {
      code: 404,
      message: 'Mock data not found',
      data: null
    };
  }

  // 获取Mock数据
  getMockData(path, method = 'GET') {
    const pathMap = {
      'POST /user/login': MockData.user.login,
      'GET /user/wechat/login/auth': MockData.user.wechatLogin,
      'GET /user/wechat/login/profile': MockData.user.getProfile,
      'PUT /user/wechat/login/profile': MockData.user.updateProfile,
      'GET /user/info': MockData.user.getUserInfo,
      'GET /video/list': MockData.video.getList,
      'GET /video/1': MockData.video.getDetail,
      'GET /post/list': MockData.community.getPostList,
      'GET /comment/list': MockData.comment.getList,
      'GET /admin/overview': MockData.admin.getOverview,
      'GET /admin/pending': MockData.admin.getPendingList
    };

    const key = `${method} ${path}`;
    return pathMap[key];
  }

  // 真实API请求（当Mock模式关闭时使用）
  async realRequest(url, options) {
    const token = wx.getStorageSync('token');
    
    return new Promise((resolve, reject) => {
      wx.request({
        url: url,
        method: options.method || 'GET',
        data: options.data || {},
        header: {
          'Content-Type': 'application/json',
          // 与真实请求保持一致：直接透传 token 字符串
          'Authorization': token || '',
          ...options.header
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: reject
      });
    });
  }

  // 切换Mock模式
  setMockMode(enabled) {
    this.isMockMode = enabled;
    console.log(`Mock模式已${enabled ? '启用' : '关闭'}`);
  }
}

// 创建全局Mock服务实例
const mockService = new MockService();

module.exports = {
  MockData,
  MockService,
  mockService
};
